package com.gitee.wsl.time.calendar

import com.gitee.wsl.time.MonthDay
import com.gitee.wsl.time.monthDay
import com.gitee.wsl.time.plusDays
import com.gitee.wsl.time.timestamp
import com.gitee.wsl.time.toLocalDate
import kotlinx.datetime.LocalDate
import kotlin.time.ExperimentalTime


class AnnualCalendar(
    baseCalendar: Calendar?=null
) : AbstractCalendar(baseCalendar) {
    /**
     * excludeDays需要按时间顺序排好序
     */
    @OptIn(ExperimentalTime::class)
    private lateinit var excludeDays: Array<MonthDay>

    @OptIn(ExperimentalTime::class)
    fun setExcludeDays(excludeDays: Array<MonthDay>) {
        this.excludeDays = excludeDays.sortedArray()
        //java.util.Arrays.sort(excludeDays)
    }

    @OptIn(ExperimentalTime::class)
    private fun isExcludedDay(day: LocalDate): Boolean {
        for (excludedDay in excludeDays) {
            if (day.month < excludedDay.month) return false

            if (day.monthDay == excludedDay) return true
        }

        return false
    }

    override fun isTimeIncluded(timeStamp: Long): Boolean {
        if (!super.isTimeIncluded(timeStamp)) {
            return false
        }

        val day: LocalDate =  timeStamp.toLocalDate()

        return !(isExcludedDay(day))
    }

    override fun getNextIncludedTime(timeStamp: Long): Long {
        var timeStamp = timeStamp
        val baseTime: Long = super.getNextIncludedTime(timeStamp)
        if ((baseTime > 0) && (baseTime > timeStamp)) {
            timeStamp = baseTime
        }

        var day = timeStamp.toLocalDate() //DateHelper.millisToDate(timeStamp)

        while (isExcludedDay(day)) {
            day = day.plusDays(1)
        }

        return day.timestamp
    }
}

fun Calendar.Companion.annualCalendar(
    baseCalendar: Calendar?=null,
    config: AnnualCalendar.() -> Unit
): AnnualCalendar {
    return AnnualCalendar(baseCalendar).apply( config)
}
